'use strict';

const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;

const db_name_comment = 'star-community-comment';
const db_name_user = 'star-community-user';
const db_name_like = 'star-community-like';
const db_comment = db.collection(db_name_comment);

exports.main = async (event, context) => {
  const flag = event.flag;

  if (flag === 0) { // id查询评论
    const {
      id,
    } = event.data;
    return await db_comment.aggregate()
      .match({
        id,
      })
      .lookup({
        from: db_name_user,
        let: {
          user_id: '$user_id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.eq(['$id', '$$user_id'])
            )
          )
          .project({
            _id: 0,
            avatar: 1,
            nickname: 1,
          })
          .done(),
        as: 'userList',
      })
      .project({
        _id: 0,
        status: 1,
        nickname: $.arrayElemAt(['$userList.nickname', 0]),
        avatar: $.arrayElemAt(['$userList.avatar', 0]),
      })
      .end();
  } else if (flag === 1) { // 查询帖子详情的评论
    const {
      my_user_id,
      post_id,
      sort,
      skip,
      limit,
    } = event.data;
    return await db_comment.aggregate()
      .match(
        dbCmd.expr(
          $.and([
            $.eq(['$post_id', post_id]),
            $.eq(['$father_id', null]),
          ])
        )
      )
      .lookup({
        from: db_name_user,
        let: {
          user_id: '$user_id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.eq(['$id', '$$user_id'])
            )
          )
          .project({
            _id: 0,
            avatar: 1,
            nickname: 1,
          })
          .done(),
        as: 'userList',
      })
      .lookup({
        from: db_name_like,
        let: {
          id: '$id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.and([
                $.eq(['$enmu_id', '$$id']),
                $.eq(['$user_id', my_user_id]),
              ])
            )
          )
          .project({
            id: 1,
          })
          .done(),
        as: 'likeList',
      })
      .project({
        _id: 0,
        id: 1,
        status: 1,
        nickname: $.arrayElemAt(['$userList.nickname', 0]),
        avatar: $.arrayElemAt(['$userList.avatar', 0]),
        commentCount: 1,
        content: 1,
        createTime: 1,
        updateTime: 1,
        imgList: 1,
        likeCount: 1,
        post_id: 1,
        user_id: 1,
        father_id: 1,
        reply_child_id: 1,
        isLiked: $.cond({
          if: {
            $gt: [
              $.size('$likeList'),
              0
            ]
          },
          then: true,
          else: false
        }),
      })
      .lookup({
        from: db_name_comment,
        let: {
          father_id: '$id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.and([
                $.eq(['$father_id', '$$father_id']),
                $.or([
                  $.and([
                    $.eq(['$user_id', my_user_id]),
                    $.in(['$status', [0, 1]])
                  ]),
                  $.eq(['$status', 1]),
                ]),
              ])
            )
          )
          .lookup({
            from: db_name_user,
            let: {
              user_id: '$user_id',
            },
            pipeline: $.pipeline()
              .match(
                dbCmd.expr(
                  $.eq(['$id', '$$user_id'])
                )
              )
              .project({
                _id: 0,
                avatar: 1,
                nickname: 1,
              })
              .done(),
            as: 'userList',
          })
          .lookup({
            from: db_name_like,
            let: {
              id: '$id',
            },
            pipeline: $.pipeline()
              .match(
                dbCmd.expr(
                  $.and([
                    $.eq(['$enmu_id', '$$id']),
                    $.eq(['$user_id', my_user_id]),
                  ])
                )
              )
              .project({
                id: 1,
              })
              .done(),
            as: 'likeList',
          })
          .lookup({
            from: db_name_comment,
            let: {
              reply_child_id: '$reply_child_id',
            },
            pipeline: $.pipeline()
              .match(
                dbCmd.expr(
                  $.eq(['$id', '$$reply_child_id'])
                )
              )
              .project({
                _id: 0,
                id: 1,
                user_id: 1,
              })
              .lookup({
                from: db_name_user,
                let: {
                  user_id: '$user_id',
                },
                pipeline: $.pipeline()
                  .match(
                    dbCmd.expr(
                      $.eq(['$id', '$$user_id'])
                    )
                  )
                  .project({
                    _id: 0,
                    id: 1,
                    nickname: 1,
                  })
                  .done(),
                as: 'userList',
              })
              .project({
                _id: 0,
                id: 1,
                status: 1,
                user_id: 1,
                nickname: $.arrayElemAt(['$userList.nickname', 0]),
                avatar: $.arrayElemAt(['$userList.avatar', 0]),
              })
              .done(),
            as: 'replyChildComment',
          })
          .unwind({
            path: '$replyChildComment',
            preserveNullAndEmptyArrays: true,
          })
          .project({
            _id: 0,
            id: 1,
            status: 1,
            nickname: $.arrayElemAt(['$userList.nickname', 0]),
            avatar: $.arrayElemAt(['$userList.avatar', 0]),
            commentCount: 1,
            content: 1,
            createTime: 1,
            updateTime: 1,
            imgList: 1,
            likeCount: 1,
            post_id: 1,
            user_id: 1,
            father_id: 1,
            reply_child_id: 1,
            replyChildComment: 1,
            isLiked: $.cond({
              if: {
                $gt: [
                  $.size('$likeList'),
                  0
                ]
              },
              then: true,
              else: false
            }),
          })
          .done(),
        as: 'commentList',
      })
      .match(
        dbCmd.expr(
          $.or([
            $.gt([
              $.size('$commentList'),
              0
            ]),
            $.and([
              $.eq(['$user_id', my_user_id]),
              $.in(['$status', [0, 1]])
            ]),
            $.eq(['$status', 1])
          ])
        )
      )
      .sort(sort)
      .skip(skip)
      .limit(limit)
      .end();
  } else if (flag === 2) { // 添加评论
    const {
      id,
      status, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
      commentCount,
      content,
      createTime,
      updateTime,
      imgList,
      likeCount,
      post_id,
      user_id,
      father_id,
      reply_child_id,
    } = event.data;
    return await db_comment.add({
      id,
      status,
      commentCount,
      content,
      createTime,
      updateTime,
      imgList,
      likeCount,
      post_id,
      user_id,
      father_id: father_id || null,
      reply_child_id: reply_child_id || null,
    });
  } else if (flag === 3) { // 更新评论
    const {
      id,
      updateData,
    } = event.data;
    return await db_comment.where({
      id
    }).update({
      ...updateData,
    });
  } else if (flag === 4) { // 查询指定状态的评论
    const {
      status,
      sort,
      skip,
      limit,
    } = event.data;
    return await db_comment.aggregate()
      .match({
        status, // 0 审核中 1 正常 2 审核不通过 3 已删除 4 已违规
      })
      .sort(sort)
      .skip(skip)
      .limit(limit)
      .lookup({
        from: db_name_user,
        let: {
          user_id: '$user_id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.eq(['$id', '$$user_id'])
            )
          )
          .project({
            _id: 0,
            avatar: 1,
            nickname: 1,
          })
          .done(),
        as: 'userList',
      })
      .project({
        _id: 0,
        id: 1,
        status: 1,
        nickname: $.arrayElemAt(['$userList.nickname', 0]),
        avatar: $.arrayElemAt(['$userList.avatar', 0]),
        commentCount: 1,
        content: 1,
        createTime: 1,
        updateTime: 1,
        imgList: 1,
        likeCount: 1,
        post_id: 1,
        user_id: 1,
        father_id: 1,
        reply_child_id: 1,
      })
      .end();
  }
};